package com.quanta.edaily.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.mapper.UserMapper;
import com.quanta.edaily.pojo.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        if(!(handler instanceof HandlerMethod)) return true;// 应该是放行静态资源的
        String token = request.getHeader("Authorization");
        if(token==null || token.isEmpty()){
            log.info("intercepted url: {}", request.getRequestURI());
            response.getWriter().write(JSON.toJSONString(JsonResponse.paramError("缺少token参数")));
            return false;
        }
        String id;
        try {
            id = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            log.info("intercepted url: {}", request.getRequestURI());
            j.printStackTrace();
            response.getWriter().write(JSON.toJSONString(JsonResponse.paramError("token验证失败")));
            return false;
        }
        User user = userMapper.getUserById(Integer.valueOf(id));
        if(user==null) {
            log.info("intercepted url: {}", request.getRequestURI());
            response.getWriter().write(JSON.toJSONString(JsonResponse.paramError("用户不存在")));
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            verifier.verify(token);
        } catch (Exception e) {
            log.info("intercepted url: {}", request.getRequestURI());
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(JsonResponse.paramError("token验证失败")));
            return false;
        }
        return true;
    }
}
